var $ = window.$;
var jade = require('jade');
var animate = require('../../util/animate');
var event = require('../../core/event');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var config = require('../../core/config');
var note = require('../note/manager');
var notify = require('../notify/ui');
var sound = require('../audio/sound');


var _inited = false;

/**
 * sample编辑
 */

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		event.bind(event.events.key.up, 'test_ui', this);
		event.lock('key','test_ui');
		_inited = true;
	},

	setManager: function (ma) {
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(param.key == 27){
			this.hide();
			return event.result.stopAll;
		}
	},

	show: function(){
		if(this.parent){
			return;
		}
		var tmpl = jade.compileFile('./tmpl/test/dialog.jade');
		var conf = {
			config: config
		};
		var html = tmpl(conf);
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_test');

		this.parent.on('click','.g_barhead i', function () {
			self.hide();
		});
		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'close'){
				var name = $('#test_name').val().trim();
				if(!name){
					notify.addNotify({
						msg: config.i18n('err05')
					});
					return;
				}
				//测试数据写入chart
				var chart = note.getNote('main');
				util.setJsonChainValue(chart, 'extra.test.name', name);
				if($('#test_current')[0].checked){
					var time = Math.round(sound.stableTime());
					util.setJsonChainValue(chart, 'extra.test.start', time);
				}else{
					util.setJsonChainValue(chart, 'extra.test.start', 0);
				}
				self.manager._doStart(name);
				self.hide();
			}
		});

		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent).then(function(){
			var chart = note.getNote('main');
			var conf = util.getJsonChainValue(chart, 'extra.test');
			if(!conf){
				return;
			}
			$('#test_name').val(conf.name || '');
		});
		event.trigger(event.events.global.blur);
	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbind(event.events.key.up, 'test_ui');
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;